// 将此文件内容复制到App.js，运行npm start即可查看效果。
import React, { useCallback, useEffect } from 'react';
import {
  ReactFlow,
  useNodesState,
  useEdgesState,
  addEdge,
} from 'reactflow';
import 'reactflow/dist/style.css';

const initialNodes = [
  { id: '1', position: { x: 0, y: 0 }, data: { label: '1' } },
  { id: '2', position: { x: 0, y: 100 }, data: { label: '2' } },
];
const initialEdges = []; // 初始边设为空数组

const storageKey = 'react-flow-data';

export default function App() {
  const [nodes, setNodes, onNodesChange] = useNodesState([]);
  const [edges, setEdges, onEdgesChange] = useEdgesState([]);

  // 初始化加载数据
  useEffect(() => {
    const loadData = () => {
      const savedData = localStorage.getItem(storageKey);
      if (savedData) {
        try {
          const { nodes: savedNodes, edges: savedEdges } = JSON.parse(savedData);
          setNodes(savedNodes || []);
          setEdges(savedEdges || []);
        } catch (e) {
          setNodes(initialNodes);
          setEdges(initialEdges);
        }
      } else {
        setNodes(initialNodes);
        setEdges(initialEdges);
      }
    };

    loadData();
  }, [setNodes, setEdges]);

  const onConnect = useCallback(
    (params) => setEdges((eds) => addEdge(params, eds)),
    [setEdges]
  );

  const handleSave = () => {
    const flowData = { nodes, edges };
    localStorage.setItem(storageKey, JSON.stringify(flowData));
    alert('保存成功');
  };

  const handleLoad = () => {
    const savedData = localStorage.getItem(storageKey);
    if (!savedData) {
      alert('没有找到保存数据');
      return;
    }

    try {
      const { nodes: loadedNodes, edges: loadedEdges } = JSON.parse(savedData);
      setNodes(loadedNodes || []);
      setEdges(loadedEdges || []);
      alert('加载成功');
    } catch (e) {
      alert('数据解析失败');
    }
  };

  return (
    <div style={{ height: '500px' }}>
      <div style={{ 
        padding: '10px',
        backgroundColor: '#f5f5f5',
        borderBottom: '1px solid #ddd'
      }}>
        <button
          onClick={handleSave}
          style={{
            marginRight: 10,
            padding: '8px 20px',
            backgroundColor: '#4CAF50',
            color: 'white',
            border: 'none',
            borderRadius: 4,
            cursor: 'pointer'
          }}
        >
          保存
        </button>
        <button
          onClick={handleLoad}
          style={{
            padding: '8px 20px',
            backgroundColor: '#2196F3',
            color: 'white',
            border: 'none',
            borderRadius: 4,
            cursor: 'pointer'
          }}
        >
          加载
        </button>
      </div>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        fitView
      />
    </div>
  );
}